"use strict";
const bag = 20;
const mvc = require('cosjs.mvc');
const dataset = require("cosjs.updater").dataset;
const promise = mvc.library.require('promise');

class item extends dataset.table {
    constructor(updater) {
        super(updater, bag, 'item');
        this.sort = 100;
        this.guid = mvc.library("guid", updater.uid, 'item');
        this._ticket = new Map();
        // this._eggTask = 0;
        this._insert_item_cache = [];
        this.updater.on("key", verify_ticket.bind(this))
        // this.updater.on("addEggTask",this_is_test.bind(this) )
    }
    data() {
        if (this._fields.size < 1) {
            return null;
        }
        return super.data().then(ret => {
            on_data_finish.call(this);
            return ret;
        })
    };

    types() {
        let ty = {};
        if (typeof arguments[0] === 'number') {
            ty['id'] = arguments[0];
            let itype = this.updater.iTypes(ty['id']);
            if (!itype['stack']) {
                throw new Error(`item[${ty['id']}] stack error`);   //不能堆叠的道具无法使用配置ID直接操作数据库,key,get,set,sub,del,add(id,key,val)
            }
            ty['_id'] = this.guid.item(ty['id']);
            ty['bag'] = itype['bag'];
        }
        else {
            ty['_id'] = arguments[0];
            ty['id'] = this.guid.parse(ty['_id']);
            let itype = this.updater.iTypes(ty['id']);
            ty['bag'] = itype['bag'];
        }
        return ty;
    }
    //格式化NEWDATA
    format(item, act) {
        item["bag"] = act.b;
        let itype = this.updater.iTypes(act['id']);
        if (itype['hooks']) {
            return this.updater.hooks([itype['hooks'], 'format'].join('/'), item, act, itype);
        }
        else {
            let f = itype["format"] ? ['item', itype["format"]] : 'item';
            return mvc.format(f, item, true);
        }
    }
    //id,key,val
    add(id) {
        if (!id || !arguments[1]) {
            return;
        }
        // this.updater.record.add(93108, 1)
        let itype = this.updater.iTypes(id);
        if (arguments.length <= 2) {
            if (itype['hooks']) {
                this.updater.hooks([itype['hooks'], 'add'].join('/'), id, arguments[1], itype);
            }
            else if (!itype['stack']) {
                this.insert(id, arguments[1]);
            }
            else {
                let config = mvc.config('item', id);
                if (config) {
                    if (config['itemCollect'] != 0 && config['itemCollect'] != undefined) {
                        this.updater.collect.max(id, 1, 3);
                    }
                }
                if (id == 60100000) {
                    this.updater.role.key('lv');
                    this.updater.role.key('exp');
                    this.updater.record.key('45');
                    return this.updater.data().then(() => {
                        let lv = this.updater.role.get('lv') || 1;
                        let exp = this.updater.role.get('exp') || 0;
                        let tempLv = lv;
                        //计算是否会升级 
                        let playerConfig = mvc.config('playerExp');
                        if (playerConfig[lv].exp != 0) {
                            let num = arguments[1];
                            exp += num;
                            let flag = false;
                            for (; exp >= 0;) {
                                if (playerConfig[lv]) {
                                    if (exp >= playerConfig[lv].exp) {
                                        exp -= playerConfig[lv].exp;
                                        lv++;
                                        flag = true;
                                        if (playerConfig[lv].exp == 0) {
                                            exp = 0;
                                            break;
                                        }
                                    } else {
                                        break;
                                    }
                                } else {
                                    break;
                                }
                            }
                            this.updater.role.set("exp", exp);
                            if (flag) {
                                this.updater.role.add("lv", lv - tempLv);
                                this.updater.record.max(45, lv);
                            }
                        }
                    });
                }
                if (id == 60100998) {
                    // 发货
                    this.updater.role.key('monthCardExpire');
                    return this.updater.data().then(() => {
                        let monthCardExpire = this.updater.role.get('monthCardExpire');
                        //因特殊情况导致重复购买，总生效时间将无法进行累加，并将直接返还330蓝星。
                        if ((monthCardExpire - Date.now()) >= 90 * 24 * 60 * 60 * 1000) {
                            this.updater.item.add(60100500, 330);

                            //特殊
                            //故意的特殊活动，要么客服主动发，要么策划配错表
                            return '已达月卡上限天数，无法购买月卡,补偿蓝星330！';

                        } else if (monthCardExpire < Date.now()) {
                            monthCardExpire = Date.now() + 30 * 24 * 60 * 60 * 1000;
                        } else monthCardExpire += 30 * 24 * 60 * 60 * 1000;

                        let montheyAwardgetConfig = mvc.config('montheyAwardget', id);
                        if (!montheyAwardgetConfig) {
                            return this.quick_error('config_not_exist', id);
                        }
                        this.updater.role.set('monthCardExpire', monthCardExpire);
                        this.act('add', id, 'val', arguments[1], itype['bag']);
                        this.updater.item.add(parseInt(montheyAwardgetConfig.monthlyBigaward), montheyAwardgetConfig.monthlyBigaward_number);
                    })
                }
                if (id == 60100997 || id == 60100996) {
                    //战令的特殊逻辑
                    // 发货
                    this.updater.role.key("battleSign");
                    return this.updater.data().then(() => {
                        let battleSignInfo = this.updater.role.get("battleSign")
                        // 检查战令是否在开放时间内
                        const now = Date.now();
                        const battlePassConfig = mvc.config("battlePassconfig", 0);
                        if (!battlePassConfig) {
                            return this.quick_error("M2PTA51", "战令数据未找到");
                        }
                        // let battlePassConfig;
                        // for (let key in battlePassConfigAll) {
                        //     battlePassConfig = battlePassConfigAll[key];
                        //     break;
                        // }
                        const beginDate = new Date(battlePassConfig.startTime).getTime();
                        const endDate = new Date(battlePassConfig.endTime).getTime();
                        if (now < beginDate || now > endDate) {
                            return this.quick_error("M2PTA51", "不在战令开放时间内");
                        }
                        //判断id是否匹配
                        if (battlePassConfig.battlePassID != battleSignInfo.ID) {
                            battleSignInfo.buyFlag = 0;
                            battleSignInfo.level = 0;
                            battleSignInfo.exp = 0; // 重置经验
                            battleSignInfo.freeReward = 0; // 重置免费奖励领取状态
                            battleSignInfo.payReward = 0; // 重置付费奖励领取状态
                        }
                        //给基础奖励
                        if (battleSignInfo.buyFlag == 0) {
                            for (let i = 0; i < battlePassConfig.basicItemDrop.length; i++) {
                                this.updater.add(battlePassConfig.basicItemDrop[i].id, battlePassConfig.basicItemDrop[i].num);
                            }
                        }
                        // 更新角色的战令数据
                        battleSignInfo.bTime = beginDate;
                        battleSignInfo.eTime = endDate;
                        if (id == 60100996) {
                            battleSignInfo.buyFlag = 2;  // 设置为已购买,0 免费,1 基础版，2 豪华版
                            //给豪华奖励
                            for (let i = 0; i < battlePassConfig.richItemDrop.length; i++) {
                                this.updater.add(battlePassConfig.richItemDrop[i].id, battlePassConfig.richItemDrop[i].num);
                            }
                        } else {
                            battleSignInfo.buyFlag = 1;  // 设置为已购买,0 免费,1 基础版，2 豪华版
                        }
                        const battleAddLevel = mvc.config("BattlePass", id);
                        if (!battleAddLevel) {
                            return this.quick_error("M2PTA51", "战令数据未找到");
                        }
                        battleSignInfo.level += battleAddLevel.levelUp; // 重置等级
                        let battleSignConfig = mvc.config("battlePassReward");
                        const maxLevel = Object.keys(battleSignConfig).length;
                        if (battleSignInfo.level > maxLevel) {
                            battleSignInfo.level = maxLevel;
                        }
                        this.updater.role.set('battleSign', battleSignInfo);
                    })
                }
                //放逐之地槽位道具ID
                if (id == 60800001) {
                    //发道具ID自动给放逐之地扩容
                    this.updater.role.key('deadAreaContainer');
                    return this.updater.data().then(() => {
                        let deadAreaContainer = this.updater.role.get('deadAreaContainer') || 10;
                        let max = mvc.config('base', 'exileMapmax').val;

                        if (!max) {
                            return this.quick_error('配置不存在');
                        }
                        if (deadAreaContainer - 10 == max) {
                            return this.quick_error('复活槽位已达上限');
                        }
                        if (deadAreaContainer + arguments[1] - 10 > max) {
                            return this.quick_error('购买数量超过该账号可获得的“放逐之地槽位”上限');
                        }
                        this.updater.role.add('deadAreaContainer', arguments[1]);
                    })

                }
                if (itype['bag'] == 62) {
                    let unitConfig = mvc.config('unitBase', id);
                    if (unitConfig) {
                        this.updater.collect.max(unitConfig.id, 1, 1);
                    }
                }
                switch (id) {
                    case 62002009:
                        this.updater.record.max(660101, 1);
                        break;
                    case 62002016:
                        this.updater.record.max(660102, 1);
                        break;
                    case 62002023:
                        this.updater.record.max(660103, 1);
                        break;

                    case 62002008:
                        this.updater.record.max(660201, 1);
                        break;
                    case 62002015:
                        this.updater.record.max(660202, 1);
                        break;
                    case 62002022:
                        this.updater.record.max(660203, 1);
                        break;

                    case 62002007:
                        this.updater.record.max(660301, 1);
                        break;
                    case 62002014:
                        this.updater.record.max(660302, 1);
                        break;
                    case 62002021:
                        this.updater.record.max(660303, 1);
                        break;
                    default:
                    // case 62002023:
                    //     this.updater.record.max(6601, 1);
                    //     break;
                    // case 62002022:
                    //     this.updater.record.max(6602, 1);
                    //     break;
                    // case 62002021:
                    //     this.updater.record.max(6603, 1);
                    //     break;
                    // default:
                }
                //判断id是不是为，60600000，60600001，60600002
                if (id == 60600000 || id == 60600001 || id == 60600002) {
                    this.updater.record.add(64, 1);
                }
                this.act('add', id, 'val', arguments[1], itype['bag']);
            }
        }
        else if (typeof id !== 'number') {
            this.act('add', id, arguments[1], arguments[2], itype['bag']);
        }
        else {
            console.log('updater.item.add  arguments error', arguments);
        }
    }
    sub(id) {
        if (!id || !arguments[1]) {
            return;
        }
        let ty = this.types(id);
        if (id == 60100500) {
            this.updater.record.add("51", arguments[1]);
            this.updater.daily.add("record.51", arguments[1]);
        }
        if (id == 60100002) {
            this.updater.record.add("69", arguments[1]);
            this.updater.daily.add("record.69", arguments[1]);
        }
        //如果id是物品组，全扣
        if (ty.bag == 70) {
            let group = mvc.config("itemGroup", id);
            if (group) {
                for (let k in group.Coll) {
                    this.sub(group.Coll[k]["key"], group.Coll[k]["num"]);
                }
            }
        } else {
            this.act('sub', ty, arguments[1], arguments[2]);
        }
    }
    exchange(id, data) {
        return this.guid.get(id).then((_id) => {
            let itype = this.updater.iTypes(id);
            if (itype) {
                let ty = { "id": id, "_id": _id }
                this.act("insert", ty, 'val', data, itype['bag']);
            }
        })
    }
    // 11003 100 11002 200
    // 11003 0 11002 100
    //
    set(id) {
        let ty = this.types(id);
        this.act('set', ty, arguments[1], arguments[2]);
    }
    del(id) {
        let ty = this.types(id);
        this.act('del', ty, arguments[1], arguments[2]);
    }

    verify() {
        if (this._insert_item_cache.length < 1) {
            return super.verify();
        }
        return this.guid.get(this._insert_item_cache).then((ret) => {
            while (this._insert_item_cache.length > 0) {
                let id = this._insert_item_cache.shift();
                let _id = ret.shift();
                let itype = this.updater.iTypes(id);
                if (itype) {
                    let ty = { "id": id, "_id": _id }
                    this.act("insert", ty, 'val', 1, itype['bag']);
                }
            }
            return super.verify();
        })
    }

    //物品组
    group(id) {
        let { err, ret } = mvc.library('item/group', id, arguments[1], arguments[2]);
        if (!err) {
            if (Array.isArray(ret)) {
                for (let d of ret) {
                    this.updater.add(d.id, d.num);
                }
            }
            else if (ret) {
                this.updater.add(ret.id, ret.num);
            }
        }
        return promise.error(err, ret);
    }
    //道具查询
    find(query) {
        query["uid"] = this.updater.uid;
        let option = { "multi": true, "dataType": "json" };
        return this.model.find(query, option).then(ret => {
            if (ret) {
                this.dataset.set(ret);
                for (let k in ret) {
                    this._history.add(k);
                }
            }
            return ret;
        });
    }
    //创建不可叠加新道具
    insert(id) {
        let val = arguments[1] || 0;
        for (let i = 1; i <= val; i++) {
            this._insert_item_cache.push(id);
        }
    }
}

module.exports = item;
//测试用
// function this_is_test(b,by){
//     this._eggTask =  .set(ty['_id'],ticket);

//     if(b != this.bag){
//         return ;
//     }
//     let ticket = mvc.config("ticket",ty['id']);
//     if(ticket){
//         this._ticket.set(ty['_id'],ticket);
//         if(ticket['mk']){
//             this.updater.role.key(ticket['mk']);
//         }
//     }
// }

//拉取数据前检查是否有门票
function verify_ticket(b, ty) {
    if (b != this.bag) {
        return;
    }
    let ticket = mvc.config("ticket", ty['id']);
    if (ticket) {
        this._ticket.set(ty['_id'], ticket);
        if (ticket['mk']) {
            this.updater.role.key(ticket['mk']);
        }
    }
}

function on_data_finish() {
    if (this._ticket.size === 0) {
        return;
    }
    for (let [_id, opt] of this._ticket) {
        console.log("on_data_finish", _id, JSON.stringify(opt))
        sum_ticket_timer.call(this, _id, opt);
    }
    this._ticket.clear();
}



//计算门票钥匙
function sum_ticket_timer(_id, opt) {
    //重置,加点
    let data = this.get(_id) || { "_id": _id, "id": opt["id"] },
        today = mvc.library("time/today"),
        week = mvc.library("time/week"),
        nowtime = this.updater.time,
        powerNum = data['val'] || 0,
        powerTime = data['lastGetTime'] || 0,
        powerMax = 0;

    powerMax = parseInt(opt["mv"]);
    // if(!opt["mk"]){
    //     powerMax = parseInt(opt["mv"]);
    // }
    // else {
    //     let ulv       = this.updater.role.get(opt["mk"])||0;
    //     let level     = mvc.config(opt['mt'],ulv) ||{};
    //     powerMax      = level[opt["mv"]] || 0;
    // }
    // console.log("sum_ticket_timer opt",JSON.stringify(opt))
    // console.log("sum_ticket_timer data",JSON.stringify(data))
    // console.log("sum_ticket_timer args",powerMax,powerNum,powerTime)

    let itype = this.updater.iTypes(data["id"]);
    if (powerNum >= powerMax) {
        //已满只更新时间
        this._acts.unshift({ "t": "set", "k": "lastGetTime", "v": nowtime, "id": data["id"], "_id": data["_id"], "b": itype.bag })
    }
    else if (!powerTime || (opt["day"] && powerTime < today)) {
        //每日回满
        this._acts.unshift({ "t": "set", "k": "lastGetTime", "v": nowtime, "id": data["id"], "_id": data["_id"], "b": itype.bag })
        this._acts.unshift({ "t": "set", "k": "val", "v": powerMax, "id": data["id"], "_id": data["_id"], "b": itype.bag })
        // this._acts.unshift({ "t": "set", "k": "*", "v": { "lastGetTime": nowtime, "val": powerMax }, "id": data["id"], "_id": data["_id"], "b": itype.bag })
    } else if (!powerTime || (opt["week"] && powerTime < week)) {
        //每周回满
        this._acts.unshift({ "t": "set", "k": "lastGetTime", "v": nowtime, "id": data["id"], "_id": data["_id"], "b": itype.bag })
        this._acts.unshift({ "t": "set", "k": "val", "v": powerMax, "id": data["id"], "_id": data["_id"], "b": itype.bag })
        // this._acts.unshift({ "t": "set", "k": "*", "v": { "lastGetTime": nowtime, "val": powerMax }, "id": data["id"], "_id": data["_id"], "b": itype.bag })
    }
    else if (nowtime > powerTime) {
        //结算时间点数
        let dotnum = opt['dot'][0] * 1000;
        let diffTime = nowtime - powerTime;
        let retnum = Math.floor(diffTime / dotnum) * opt['dot'][1];
        console.log("sum_ticket_timer rets", _id, diffTime, dotnum, retnum)
        if (retnum > 0) {
            powerNum = Math.min(powerNum + retnum, powerMax);
            powerTime += retnum * dotnum;
            this._acts.unshift({ "t": "set", "k": "lastGetTime", "v": powerTime, "id": data["id"], "_id": data["_id"], "b": itype.bag })
            this._acts.unshift({ "t": "set", "k": "val", "v": powerNum, "id": data["id"], "_id": data["_id"], "b": itype.bag })
            // this._acts.unshift({ "t": "set", "k": "*", "v": { "lastGetTime": powerTime, "val": powerNum }, "id": data["id"], "_id": data["_id"], "b": itype.bag })
            // this._acts.unshift({ "t": "set", "k": "*", "v": { "lastGetTime": powerTime, "val": powerNum }, "id": data["id"], "_id": data["_id"], "b": itype.bag })
        }
    }
}
